import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_deer/card_reader.dart';
import 'package:flutter_deer/database/beans/pending_order_bean.dart';
import 'package:flutter_deer/database/database_manager.dart';
import 'package:flutter_deer/database/tables.dart';
import 'package:flutter_deer/dl/dl.dart';
import 'package:flutter_deer/generated/res_upload_oil_entity.dart';
import 'package:flutter_deer/mvvm/base_page_mvvm.dart';
import 'package:flutter_deer/objectbox.g.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/res/dimens.dart';
import 'package:flutter_deer/res/gaps.dart';
import 'package:flutter_deer/ui/cashier/dialog/diaog_card_pay.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:flutter_deer/util/aes_cbc_util.dart';
import 'package:flutter_deer/util/change_notifier_manage.dart';
import 'package:flutter_deer/util/input_formatter/mny_format.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/widgets/dialog/goods_selection_dialog.dart';
import 'package:flutter_deer/widgets/my_refresh_list.dart';
import 'package:flutter_deer/widgets/popup_window.dart';
import 'package:flutter_deer/widgets/press_blue_button.dart';
import 'package:flutter_deer/widgets/search_box.dart';
import 'package:get/get.dart';

import 'dialog/match_pre_pay_list_dialog.dart';
import 'dialog/merge_oil_order_dialog.dart';
import 'dialog/take_orders_dialog.dart';
import 'item/cashier_order_buy_item.dart';
import 'item/cashier_order_item_header.dart';

class CashierPageMid extends StatefulWidget {
  const CashierPageMid({super.key});

  @override
  State<CashierPageMid> createState() => _CashierPageMidState();
}

class _CashierPageMidState extends State<CashierPageMid> with ChangeNotifierMixin<CashierPageMid>, BasePageMvvm<CashierPageMid> {
  final GlobalKey _addKeyInput = GlobalKey();

  final mProvider = Get.find<CashierPageProvider>();

  @override
  void initState() {
    super.initState();
    _listenPendingOrders();
    mProvider.requestAdvanceOrderStatisticsPage();
  }

  @override
  void dispose() {
    _subscription.cancel();
    _objectIdBox.dispose();
    super.dispose();
  }

  void _onViewClick(String text) {
    print('点击了：$text');
  }

  late ObjectIdBox _objectIdBox;
  late StreamSubscription<dynamic> _subscription;
  RxInt pendingOrderCount = 0.obs;

  // 监听挂单
  Future<void> _listenPendingOrders() async {
    //监听数据库变化
    _objectIdBox = getIt<ObjectIdBox>();
    final Store store = await _objectIdBox.storeAsync; // 等待初始化完成
    final box = store.box<PendingOrderBean>();
    _subscription = store
        .box<PendingOrderBean>()
        .query()
        .watch(triggerImmediately: false)
        .listen((changes) {
      final list = box.query().build().find();
      pendingOrderCount.value = list.length;
      print('挂单：${list.length} changes--$changes');
    });
    final list = box.query().build().find();
    pendingOrderCount.value = list.length;
  }

  // 显示商品选择对话框
  void _showGoodsDialog() {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return const GoodsSelectionDialog();
      },
    );
  }

  // 合并油单
  void _showMergeOilOrder() {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return const MergeOilOrderDialog();
      },
    );
  }

  // 预付款
  void _showAdvanceOrder() {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return const MatchPrePayListDialog();
      },
    );
  }

  // 挂单
  void _showHangOrder() {
    final PendingOrderBean mBean = PendingOrderBean();
    mBean.createTime = Utils.getCurrentTime();

    final List<Map<String, dynamic>> goodsJsonList = mProvider.selectListGoods.map((goods) => goods.toJson()).toList();
    mBean.goodsList = json.encode(goodsJsonList);

    final List<Map<String, dynamic>> oilJsonList = mProvider.selectListOils.map((oil) => oil.toJson()).toList();
    mBean.oilList = json.encode(oilJsonList);

    mBean.descMny = mProvider.totalOrderAmountRx.toString();

    mBean.descShop = mProvider.selectListGoods.take(5).map((e) => e.goodsName).join(',');

    mBean.descOil = mProvider.selectListOils.take(2).map((e) => e.toStringTake()).join(',');

    mBean.phone = mProvider.memberInfo?.phone ?? '';

    mBean.save();

    final mList = <ResUploadOilEntity> [];
    for (final value in mProvider.selectListOils) {
      final mEntity = ResUploadOilEntity();
      mEntity.energyOrderCode = value.energyOrderCode;
      mEntity.suspendTime = mBean.createTime;
      mList.add(mEntity);
    }
    AppOrderBean.updatePendingTime(mList);

    mProvider.reset();

    Toast.show('挂单成功');
  }

  // 真的执行取单操作
  void takeOrder() {

  }

  // 取单弹窗
  void _showTakeOrder() {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return const TakeOrdersDialog();
      },
    );
  }

  // 读卡
  void _readCard() {
    // scanResult.value = '读卡中...';
    CardReader.readUid().then((value) {
      print('读卡：$value ${AESCBCUtil.decrypt(value['data'])}');
      // scanResult.value = '$value ${AESCBCUtil.decrypt(value['data'])}';
      mProvider.requestMemberInfo(cardNo: value['data'], uuId: value['uid'], onGiftCard: () {
        _showCardPayDialog();
      });
      // mProvider.requestMemberInfo(cardNo: AESCBCUtil.encrypt('102400000056'), uuId: value['uid']);
    }).catchError((error) {
      // scanResult.value = '读卡失败: $error';
      Toast.show('读卡失败: $error');
    });
  }

  void _showCardPayDialog() {
    mProvider.refreshDiscount(successCallback: (list){
      mProvider.mCardList.assignAll(list);
      showDialog<void>(
        context: context,
        barrierDismissible: false, // 点击背景不消失
        builder: (BuildContext context) {
          return AlertDialog(
            contentPadding: EdgeInsets.zero,
            content: SizedBox(
              width: MediaQuery.of(context).size.width * 0.6,
              height: MediaQuery.of(context).size.height * 0.7,
              child: const DialogCardPay(),
            ),
          );
        },
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const CashierOrderItemHeader(),

        // 油品列表
        Obx(() => ColoredBox(
              color: Colors.white, // 可选：方便看到区域
              child: ListView.builder(
                shrinkWrap: true, // 让列表根据内容自适应高度
                physics: const NeverScrollableScrollPhysics(), // 禁止列表滚动
                itemCount: mProvider.selectListOils.length,
                itemBuilder: (_, index) {
                  return CashierOrderBuyItem(
                    itemOil: mProvider.selectListOils[index],
                  );
                },
              ),
            )),

        // 便利店
        Expanded(
          child: Obx(() => Container(
                color: Colors.white, // 可选：方便看到区域
                // alignment: Alignment.center,
                child: DeerListView(
                    itemCount: mProvider.selectListGoods.length,
                    onRefresh: () => Future.value(),
                    itemBuilder: (_, index) {
                      return CashierOrderBuyItem(
                        itemGoods: mProvider.selectListGoods[index],
                      );
                    }),
              )),
        ),

        // 按钮
        Container(
          decoration: const BoxDecoration(
            // color: Colors.white,
            // color: Color(0xFFFF8547),
            color: Colours.blueE8F2FF,
            borderRadius: BorderRadius.only(bottomRight: Radius.circular(3), bottomLeft: Radius.circular(3)),
            // border: Border(
            //   bottom: Divider.createBorderSide(context, width: 0.8, color: Colours.line),
            // ),
          ),
          padding: const EdgeInsets.only(left: 0, bottom: 6, top: 6, right: 0),
          child: Obx(() => Row(
                children: [
                  // 常用商品
                  const SizedBox(width: 5),
                  PressBlueButton(text: '常用商品', onPressed: () => _showGoodsDialog()),
                  // 油单收款
                  // const SizedBox(width: 5),
                  // PressBlueButton(text: '油品收款', onPressed: () => _onViewClick('油品收款')),
                  // 挂单
                  if (mProvider.selectListOils.isNotEmpty || mProvider.selectListGoods.isNotEmpty) const SizedBox(width: 5),
                  if (mProvider.selectListOils.isNotEmpty || mProvider.selectListGoods.isNotEmpty) PressBlueButton(text: ' 挂 单 ', onPressed: () => _showHangOrder()),
                  // 取单
                  if (mProvider.selectListOils.isEmpty && mProvider.selectListGoods.isEmpty) const SizedBox(width: 5),
                  if (mProvider.selectListOils.isEmpty && mProvider.selectListGoods.isEmpty) PressBlueButton(text: '取单（$pendingOrderCount）', onPressed: () => _showTakeOrder()),
                  // 预付款
                  const SizedBox(width: 5),
                  PressBlueButton(text: '预付款${mProvider.advanceOrderCount}', onPressed: () => _showAdvanceOrder()),
                  // 合并支付
                  if (mProvider.selectListOils.length == 1) const SizedBox(width: 5),
                  if (mProvider.selectListOils.length == 1) PressBlueButton(text: '合并支付', onPressed: () => _showMergeOilOrder()),
                ],
              )),
        ),

        Gaps.vGap4,

        // 会员区
        Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            // color: Color(0xFFFF8547),
            // color: Colours.dark_app_main,
            // borderRadius: BorderRadius.only(bottomLeft: Radius.circular(3), bottomRight: Radius.circular(3)),
            borderRadius: BorderRadius.all(Radius.circular(3)),
            // border: Border(
            //   bottom: Divider.createBorderSide(context, width: 0.8, color: Colours.line),
            // ),
          ),
          padding: const EdgeInsets.only(left: 5.0, bottom: 5.0, top: 5, right: 5.0),
          child: Column(
            children: [
              // 点击登录框
              SearchBox(
                key: _addKeyInput,
                hintText: '请刷加油卡，扫小程序会员码/或输入手机号...',
                inputType: TextInputType.number,
                // 点击事件
                onSubmitted: (text) {
                  mProvider.requestMemberInfo(phone: text);
                },
                // onTap: () {
                //   // 导航到搜索页面
                //   Toast.show('点击了搜索');
                // },
              ),

              // 会员基本信息
              Obx(() => Row(
                    // 垂直方向基于基线对齐
                    crossAxisAlignment: CrossAxisAlignment.baseline,
                    // 指定使用字母基线
                    textBaseline: TextBaseline.alphabetic,
                    // 水平方向左右对齐
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // 会员基本信息
                      Row(
                        // 水平方向居中对齐
                        mainAxisAlignment: MainAxisAlignment.center,
                        // 垂直方向基于基线对齐
                        crossAxisAlignment: CrossAxisAlignment.baseline,
                        // 指定使用字母基线
                        textBaseline: TextBaseline.alphabetic,
                        children: [
                          // name
                          Text(
                            '${mProvider.memberInfo?.nickname ?? ' - '}',
                            style: const TextStyle(
                              fontSize: Dimens.font_sp18,
                              // fontWeight: FontWeight.bold,
                              color: Colours.text,
                              height: 1.9,
                            ),
                          ),
                          // Vol
                          Text(
                            ' / ${mProvider.memberInfo?.phone ?? ' - '}',
                            style: const TextStyle(
                              fontSize: Dimens.font_sp16,
                              color: Colours.text,
                            ),
                          ),

                          const SizedBox(width: 10),

                          Container(
                            // width: double.infinity,
                            // height: 200,
                            // 圆角设置为4
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(4),
                              // 渐变背景
                              gradient: const LinearGradient(
                                colors: [
                                  Colours.grey4B4B4F,
                                  Colours.grey48484A,
                                  Colours.grey0A0A0A,
                                ],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              ),
                            ),
                            // 内容居中

                            child: Padding(
                              padding: const EdgeInsets.only(left: 6.0, right: 6.0, top: 2.0, bottom: 2.0),
                              child: Text(
                                mProvider.memberInfo?.levelName ?? '-',
                                style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: Dimens.font_sp14,
                                  // fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),

                      // 切换按钮
                      Row(
                        // 水平方向居中对齐
                        mainAxisAlignment: MainAxisAlignment.center,
                        // 垂直方向基于基线对齐
                        crossAxisAlignment: CrossAxisAlignment.baseline,
                        // 指定使用字母基线
                        textBaseline: TextBaseline.alphabetic,
                        children: [
                          // Money
                          PressBlueButton(
                            defaultColor: Colours.blue13345F,
                            text: '刷实体卡',
                            onPressed: () => _readCard(),
                          ),

                          const SizedBox(width: 5),

                          PressBlueButton(
                            defaultColor: Colours.blue13345F,
                            text: '用户退出',
                            onPressed: () => mProvider.logout(),
                          ),
                        ],
                      ),
                    ],
                  )),

              // 间隔
              Gaps.vGap5,

              // 会员信息列表展示
              Obx(() => Container(
                    width: double.infinity,
                    // 固定宽度
                    // height: 80,
                    // 固定高度
                    padding: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      color: Colors.blue[100],
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Wrap(
                      spacing: 8.0, // 子组件之间的水平间距
                      runSpacing: 8.0, // 子组件之间的垂直间距
                      children: [
                        // 添加多个子组件
                        buildItem('积分：${mProvider.memberInfo?.memberIntegral?.accountBalance ?? ''}'),
                        buildItem('账户余额：${mProvider.memberInfo?.accountSumInfoResponse?.indAccountAmountSum?.toYuan ?? '-'}元'),
                        buildItem('冻结余额：${mProvider.memberInfo?.accountSumInfoResponse?.freezeAccountAmountSum ?? '-'}元'),
                        buildItem('标签/车队：${mProvider.memberInfo?.simpleTagInfoResponses?.map((s) => s.tagName).join('，') ?? ''}'),
                        buildItem('车牌：${mProvider.memberInfo?.memberPlates?.where((element) => element.plateNo?.isNotEmpty == true).map((s) => s.plateNo).join('，') ?? ''}'),
                      ],
                    ),
                  )),
            ],
          ),
        ),

        //用户信息
      ],
    );
  }

  // 构建单个子项
  Widget buildItem(String text) {
    return InkWell(
        onTap: () {
          // 可选：点击也显示
          _showTooltip(context, text);
        },
        child: Container(
          width: 193,
          padding: const EdgeInsets.only(left: 0, right: 0, top: 1, bottom: 1),
          child: Text(
            text,
            style: const TextStyle(fontSize: Dimens.font_sp14),
            textAlign: TextAlign.start,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ));
  }

  void _showTooltip(BuildContext context, String message) {
    showDialog<void>(
      context: context,
      barrierDismissible: true, // 点击遮罩可关闭
      builder: (context) {
        return AlertDialog(
          content: Text(message),
          contentPadding: const EdgeInsets.all(12),
          insetPadding: EdgeInsets.zero, // 靠近文本显示
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        );
      },
    );
  }

  @override
  Map<ChangeNotifier?, List<VoidCallback>?>? changeNotifier() {
    return null;
  }
}
